package com.his.modules.sysjob.util;

import com.his.modules.sysjob.entity.SysJob;
import com.his.modules.sysjob.entity.SysJobLog;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.BeanUtils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;
import java.util.concurrent.*;

/**
 * 定时任务处理
 *
 */
@DisallowConcurrentExecution
@Slf4j
public class ScheduleJob extends QuartzJobBean
{

    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context)
    {
        SysJob job = new SysJob();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES),job);

        SysJobLog jobLog = new SysJobLog();
        jobLog.setJobName(job.getJobName());
        jobLog.setJobGroup(job.getJobGroup());
        jobLog.setMethodName(job.getMethodName());
        jobLog.setMethodParams(job.getMethodParams());
        jobLog.setCreateTime(LocalDateTime.now());

        long startTime = System.currentTimeMillis();

        try
        {
            // 执行任务
            log.info("任务开始执行 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
            ScheduleJobCallable task = new ScheduleJobCallable(job.getJobName(), job.getMethodName(), job.getMethodParams());
            Future<?> future = service.submit(task);
			future.get();
			long times = System.currentTimeMillis() - startTime;
			// 任务状态 0：成功 1：失败
			jobLog.setStatus(ScheduleConstants.SUCCESS);
			jobLog.setJobMessage(job.getJobName() + " 总共耗时：" + times + "毫秒");
			log.info("任务执行结束 - 名称：{} 耗时：{} 毫秒", job.getJobName(), times);
        } catch (Exception e) {
            log.info("任务执行失败 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
            log.error("任务执行异常  - ：", e);
            long times = System.currentTimeMillis() - startTime;
            jobLog.setJobMessage(job.getJobName() + " 总共耗时：" + times + "毫秒");
            // 任务状态 0：成功 1：失败
            jobLog.setStatus(ScheduleConstants.FAIL);
            jobLog.setExceptionInfo(e.getMessage());
            if(e.getCause() != null && e.getCause().getCause() != null && StringUtils.isNotBlank(e.getCause().getCause().getMessage())) {
				jobLog.setExceptionInfo(e.getCause().getCause().getMessage());
			}
        }
        finally
        {
			jobLog.insert();
        }
    }
}
